package com.example.sso.server;

import cn.dev33.satoken.config.SaSsoConfig;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.sso.SaSsoProcessor;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.dtflys.forest.Forest;
import com.example.sso.server.entity.SysAccount;
import com.example.sso.server.service.SysAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.sso.server;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2024-01-23 18:48]
 * @copyright: 2024 echovin.com
 */

@RestController
public class SsoServerController {
    @Resource
    private SysAccountService sysAccountService;

    @RequestMapping("/sso/*")
    public Object ssoRequest() {
        return SaSsoProcessor.instance.serverDister();
    }

    @Autowired
    private void configSso(SaSsoConfig sso) {
        // 配置：未登录时返回的View
        sso.setNotLoginView(()->{
            return new ModelAndView("sa-login.html");
        });

        // 配置：登录处理函数
        sso.setDoLoginHandle((name, pwd) -> {
            // 此处仅做模拟登录，真实环境应该查询数据进行登录
            SysAccount sysAccount = sysAccountService.selectByAccount(name);
            if (sysAccount == null){
                return SaResult.error("账户不存在！");
            }
            if(sysAccount.getPwd().equals(pwd)) {
                StpUtil.login(sysAccount.getId());
                return SaResult.ok("登录成功！").setData(StpUtil.getTokenValue());
            }
            return SaResult.error("登录失败！");
        });

        // 配置 Http 请求处理器 （在模式三的单点注销功能下用到，如不需要可以注释掉）
        sso.setSendHttp(url -> {
            try {
                // 发起 http 请求
                return Forest.get(url).executeAsString();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        });
    }
}
